/*
 * Copyright (C) 2014 luke.
 * 
 * This file is part of Silvie.
 * 
 * Silvie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Silvie is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Silvie.  If not, see <http://www.gnu.org/licenses/>.
 */

package silvie.resources.chrmodel.chunks;

import java.awt.Image;

import silvie.Silvie;
import utils.DataReader;
import utils.PalettizedImage;

/**
 * AbstractChunk specialization for the "texture" chunk.
 * 
 * @author luke
 */
public class Chunk0x7f04 extends AbstractChunk {
	private static final int MISSING_INDEX_COUNT = 8;
	private static final int HEADER_SIZE_OFFSET = 24;
	private static final int HEIGHT_OFFSET = 8;
	private static final int WIDTH_OFFSET = 4;
	private int width;
	private int height;
	private Image texture;
	private short[] texturePixelIndices;

	/**
	 * Chunk0x7f04 constructor.
	 * 
	 * @see AbstractChunk#AbstractChunk(int, byte[])
	 */
	public Chunk0x7f04(int id, byte[] data) {
		super(id, data);
	}

	@Override
	public int decode() {
		this.width = DataReader.readInt(super.data, WIDTH_OFFSET);
		this.height = DataReader.readInt(super.data, HEIGHT_OFFSET);
		int headerSize = DataReader.readInt(super.data, HEADER_SIZE_OFFSET);
		int pixelCount = this.width * this.height;
		/*
		 * Silver bug: for some reason all model textures are missing their last
		 * 8 pixels. Using a texture ripper directly on the game showed that the
		 * game's texture loader "overreads" the last 8 indices of the texture
		 * on the first 8 bytes of the 0x7f05 chunk.
		 */
		short[] bogusPixelIndices = DataReader.readIndices(super.data, headerSize, pixelCount - MISSING_INDEX_COUNT);
		this.texturePixelIndices = new short[pixelCount];
		System.arraycopy(bogusPixelIndices, 0, this.texturePixelIndices, 0, pixelCount - MISSING_INDEX_COUNT);
		PalettizedImage palettizedImage = new PalettizedImage(this.width, this.height, Silvie.FIXED_PALETTE, this.texturePixelIndices);
		this.texture = palettizedImage.createImage();
		return super.data.length;
	}

	public short[] getTexturePixelIndices() {
		return this.texturePixelIndices;
	}

	public int getWidth() {
		return this.width;
	}

	public int getHeight() {
		return this.height;
	}

	public Image getTexture() {
		return this.texture;
	}
}
